#!/bin/bash
# Copyright (c) 2022 maminjie <canpool@163.com>
# SPDX-License-Identifier: MulanPSL-2.0


usage() {
printf "Cherry pick A branch commit to B branch

usage:
    bash $0 PATCH_DIR [OPTIONS]

params:
    PATCH_DIR - the dir of patches those generated from A branch
    OPTIONS - cherry-pick option, such as: -x -s

process:
    1) git checkout A_BRANCH (not necessary)
        If the current repository does not have A_BRANCH, you can use git remote add remote repository:
            run \"git remote add REMOTE_NAME REMOTE_URL\"
            run \"git fetch REMOTE_NAME\"
            run \"git checkout remote/XXX -b A_BRANCH\"

    2) git format-patch -o PATCH_DIR COMMIT..HEAD
        or
       git format-patch A_BRANCH -o PATCH_DIR COMMIT1..COMMIT2

    3) git checkout B_BRANCH

    4) bash $0 PATCH_DIR
        If there is a conflict, resolve it and continue executing the script:
            run \"git status\"
            see log and resolve conflict
            run \"git add ...\"
            run \"git cherry-pick --continue\"
            run \"bash $0 PATCH_DIR\"
\n"
}

main() {
    local patch_dir="$1"
    if [ ! -d "$patch_dir" ]; then
        usage; exit
    fi
    shift 1
    local options="$@"
    [[ ! -d "$patch_dir/ok" ]] && mkdir -p $patch_dir/ok
    [[ ! -d "$patch_dir/fail" ]] && mkdir -p $patch_dir/fail
    [[ ! -d "$patch_dir/empty" ]] && mkdir -p $patch_dir/empty
    [[ ! -d "$patch_dir/allow-empty" ]] && mkdir -p $patch_dir/allow-empty

    for f in $(ls -1 $patch_dir/*.patch | sort -g); do
        if [ -s "$f" ]; then
            local id=$(head -n1 $f | awk '{print $2}')
            git cherry-pick $options $id  &> log
            if [ $? -ne 0 ]; then
                grep "git commit --allow-empty" log > /dev/null
                if [ $? -ne 0 ]; then
                    echo "$f failed"
                    mv $f $patch_dir/fail
                    git log -1 $id
                    break
                else
                    echo "$f empty"
                    git cherry-pick --abort
                    mv $f $patch_dir/allow-empty
                fi
            else
                echo "$f ok"
                mv $f $patch_dir/ok
            fi
            rm -f log
        else
            echo "$f empty"
            mv $f $patch_dir/empty
        fi
    done
}


main "$@"
